package com.culture.config.common.filter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class FilterResponseWrapper extends HttpServletResponseWrapper {
    private HttpServletResponse response;    
    private ByteArrayOutputStream buffer = null;
    private ServletOutputStreamWrapper outputStreamWrapper;
    private PrintWriter writer = null;

    public FilterResponseWrapper(HttpServletResponse response) throws UnsupportedEncodingException {
        super(response);
        this.response = response;
        this.initFilter();
    }

    private void initFilter() throws UnsupportedEncodingException {
        this.buffer = new ByteArrayOutputStream();
        this.outputStreamWrapper = new ServletOutputStreamWrapper(this.buffer);
        this.writer = new PrintWriter(new OutputStreamWriter(this.buffer, this.response.getCharacterEncoding()));
    }    
   
    @Override
    public ServletOutputStream getOutputStream() {
        return this.outputStreamWrapper;
    }

    @Override
    public PrintWriter getWriter() throws UnsupportedEncodingException {
        return writer;
    }

    /**
     * last flush output buffer
     * 
     * @throws IOException
     */
    @Override
    public void flushBuffer() throws IOException {
         if (outputStreamWrapper != null) {
            outputStreamWrapper.flush();
         }
         if (writer != null) {
             writer.flush();
         }
     } 
 
     @Override
     public void reset() {
        outputStreamWrapper.reset();
     } 
 
     public byte[] getResponseData() throws IOException {
         flushBuffer();
         return buffer.toByteArray();
     }
}